import React, { useEffect } from 'react';
import { Button, Form, Input, message, Spin, Select } from 'antd';
import { connect } from 'umi';
import { useTablePipeline } from 'ali-react-table';
import { useDebounceFn } from 'ahooks';
import { HttpCode } from '#/utils/contacts.js';
import styles from './index.less';
import { getColumns } from '../helper';
import { useTRState } from '#/utils/trHooks';
import { AntdBaseTable } from '@/base/TBaseTable';
import ApplyModal from '../components/editModel/index';
import {
  placeInfo,
  placeInfoAdd,
  placeInfoEdit,
  placeInfoDel,
  machineInfo,
  dimStationInfo,
  queryMarketList,
} from '../service';
import { postQueryProvinceList } from '@/services/user';
import { TRCheckboxModal } from '@/components/index.js';
import { getTreeByCodes } from '@/utils';
// 处理交易单元数据
export const getDealElementOptions = (data) => {
  const _settlemen = {};
  let dataObj = {};
  const modalData = data.map((m) => {
    const _children = m?.children?.map((item) => {
      const children = item?.children?.map((n) => ({
        ...n,
        title: n?.stationName,
        key: n?.stationId,
        parentKey: n?.groupId,
        regionId: n?.marketId || '',
      }));
      dataObj = { ...dataObj, ..._.groupBy(children, 'value') };
      _settlemen[`${item?.marketId}-${item?.groupId}`] = children;
      return {
        ...item,
        key: `${item?.marketId}-${item?.groupId}`,
        title: item?.groupName || '',
        children,
        parentKey: item?.marketId,
      };
    });
    return { ...m, title: m?.marketName || '', children: _children, key: m?.marketId || '' };
  });
  return { modalData, value: _.flatten(Object.values(_settlemen)), dataObj };
};
const placeType = ({ menuCode, buttonPermissions }) => {
  const [state, setState] = useTRState({
    dataSource: [],
    rowData: {},
    applyType: 'add',
    showApply: false,
    loading: true,
    machineInfo: [],
    dimStationInfo: [],
    dimStationOptions: [],
    treeSelectedIds: [],
    nowIds: [],
    modalData: [],
    buttonPower: {
      add: false,
      edit: false,
      delete: false,
    },
  });
  const [form] = Form.useForm();
  useEffect(async () => {
    fetch();
    let buttonPower = { add: false, edit: false, delete: false };
    buttonPermissions.map((item) => {
      if (item.menuCode == 'UnitAssAdd') buttonPower.add = true;
      if (item.menuCode == 'UnitAssEdit') buttonPower.edit = true;
      if (item.menuCode == 'UnitAssDel') buttonPower.delete = true;
    });
    setState({
      buttonPower,
    });
  }, []);
  const fetch = async (stationIdList = []) => {
    let stationIds = [...stationIdList];
    setState({
      loading: true,
    });
    let machineData = [];
    let dimStationOptions = [];
    let dimStationData = [];
    if (state.machineInfo.length < 1) {
      const ress = await Promise.all([
        machineInfo({ size: 999 }),
        dimStationInfo(),
        queryMarketList(menuCode),
      ]);
      if (
        ress[0]?.statusCode === HttpCode.SUCCESS &&
        ress[1]?.statusCode === HttpCode.SUCCESS &&
        ress[2]?.statusCode === HttpCode.SUCCESS
      ) {
        machineData = ress[0].data;
        dimStationData = ress[1].data;
        const power = getTreeByCodes(['market', 'group', 'station'], ress[2].json).treeOptions;
        let dimStation = getDealElementOptions(power);
        stationIds = dimStation.value.map((item) => item.value);
        dimStationOptions = dimStation.value;
        setState({
          machineInfo: ress[0].data,
          dimStationInfo: ress[1].data,
          dimStationOptions: dimStationOptions,
          modalData: dimStation.modalData,
          treeSelectedIds: stationIds,
        });
      } else if (ress[2]?.statusCode !== HttpCode.SUCCESS) {
        message.error(res?.message || '请联系管理员获取数据相关权限');
      }
    } else {
      machineData = [...state.machineInfo];
      dimStationData = [...state.dimStationInfo];
      dimStationOptions = [...state.dimStationOptions];
    }
    const res = await placeInfo({ stationIdList: stationIds, size: 999 });
    if (res?.statusCode === HttpCode.SUCCESS) {
      let data = res.data.map((item) => {
        let obj = { ...item };
        machineData.map((x) => {
          if (x.unitType == item.unitType) {
            obj.ratedPower = x.ratedPower;
            obj.cutoutWindspeed = x.cutoutWindspeed;
          }
        });
        dimStationData.map((x) => {
          if (x.stationId == item.stationId) {
            obj.stationCapacity = x.stationCapacity;
          }
        });
        dimStationOptions.map((x) => {
          if (x.value == item.stationId) {
            obj.stationName = x.label;
          }
        });
        return obj;
      });
      setState({
        nowIds: stationIds,
        dataSource: data,
      });
    } else {
      message.error(res?.message);
    }
    setState({
      loading: false,
    });
  };
  const _onReset = useDebounceFn(
    () => {
      form.resetFields();
      TRCheckboxModal.dismiss();
      setState({
        treeSelectedIds: state.dimStationOptions.map((item) => item.value),
      });
      let stationIdList = state.dimStationOptions.map((item) => item.value);
      fetch(stationIdList);
    },
    { wait: 500 },
  );
  const _onFinish = useDebounceFn(
    (values) => {
      let stationIdList = [];
      if (!!values.stationId) {
        (state.treeSelectedIds.length > 0 ? state.treeSelectedIds : state.dimStationOptions).map(
          (item) => {
            let value = state.treeSelectedIds.length > 0 ? item : item.value;
            if (value.indexOf(values.stationId) >= 0) {
              stationIdList.push(value);
            }
          },
        );
      } else {
        stationIdList =
          state.treeSelectedIds.length > 0
            ? state.treeSelectedIds
            : state.dimStationOptions.map((item) => item.value);
      }
      fetch(stationIdList);
    },
    { wait: 500 },
  );
  const rowClick = async (type, row = []) => {
    if (!state.buttonPower[type]) {
      return message.info('请联系管理员获取相关权限');
    }
    if (type == 'edit' || type == 'add') {
      setState({
        applyType: type,
        rowData: row,
        showApply: true,
      });
    } else {
      setState({
        loading: true,
      });
      const res = await placeInfoDel([row.id]);
      if (res?.statusCode === HttpCode.SUCCESS) {
        message.success('删除成功！');
        fetch(state.nowIds);
      } else {
        message.error(res?.message);
      }
      setState({
        loading: false,
      });
    }
  };
  const save = (values) => {
    let forms = { ...values };
    if (state.applyType == 'edit') {
      forms.id = state.rowData.id;
      forms.fanNo = state.rowData.fanNo;
      forms.manufactor = state.rowData.manufactor;
    } else {
      forms.manufactor = '';
      forms.fanNo = '';
    }
    forms.stationId = forms.stationName;
    delete forms.cutoutWindspeed;
    delete forms.ratedPower;
    delete forms.stationName;
    delete forms.stationCapacity;
    return state.applyType == 'add' ? placeInfoAdd([forms]) : placeInfoEdit([forms]);
  };
  const pipeline = useTablePipeline({ components: {} })
    .input({
      dataSource: state.dataSource,
      columns: getColumns({
        type: 'placeType',
        onChange: rowClick,
        buttonPower: state.buttonPower,
      }),
    })
    .primaryKey('id');

  const _renderHeader = () => {
    return (
      <div className={styles.header}>
        <div style={{ display: 'flex', marginRight: 12 }}>
          {/* <Button loading={state.loading}
            htmlType="primary" style={{ marginRight: 12 }} >

          </Button> */}
          <Select
            style={{ width: 190 }}
            value={
              !state.treeSelectedIds.length
                ? '场站筛选'
                : state.treeSelectedIds.length === state.dimStationOptions.length
                ? '全部'
                : `${state.treeSelectedIds.length}项/${state.dimStationOptions.length}项`
            }
            open={false}
            onClick={async () => {
              const result = await TRCheckboxModal.show({
                title: '场站筛选',
                value: state.treeSelectedIds,
                treeData: state.modalData,
                okText: '提交',
              });
              if (result?.index === 1) {
                setState({
                  treeSelectedIds: result.checkedKeys,
                });
              }
            }}
          />
          <Form
            form={form}
            className={styles.formStyles}
            onFinish={_onFinish.run}
            autoComplete="off"
          >
            <Form.Item name="stationId" className={styles.cell_item}>
              <Input placeholder="请输入场站编码" />
            </Form.Item>
            <Button className={styles.submit} type="primary" htmlType="submit">
              查询
            </Button>
            {/* </Popconfirm> */}
            <Button className={styles.reset} htmlType="reset" onClick={_onReset.run} ghost>
              重置
            </Button>
          </Form>
        </div>
        <Button
          className={[styles.reset, !state.buttonPower['add'] ? styles.disableBtn : '']}
          htmlType="primary"
          onClick={() => rowClick('add')}
        >
          新增
        </Button>
      </div>
    );
  };
  return (
    <div>
      {_renderHeader()}
      <Spin spinning={state.loading}>
        <AntdBaseTable
          className={['bordered', 'dark', `${styles.custor}`].join(' ')}
          style={{
            // '--header-bgcolor': '#383C3E',
            '--header-color': 'white',
            '--row-height': '22px',
            '--header-row-height': '58px',
            '--bgcolor': '#222629',
            '--color': '#D3D4D4',
            '--cell-padding': '3px 16px',
            '--hover-bgcolor': '#222629',
          }}
          {...pipeline.getProps()}
          defaultColumnWidth={81}
          useVirtual={{ horizontal: false, vertical: true, header: false }}
        />
      </Spin>
      <ApplyModal
        showApply={state.showApply}
        onClose={(bool = false) => {
          setState({ showApply: false });
          if (bool) {
            fetch(state.nowIds);
          }
        }}
        config={{
          machineInfo: state.machineInfo,
          dimStationInfo: state.dimStationInfo,
          dimStationOptions: state.dimStationOptions,
        }}
        onOk={save}
        type="place"
        data={state.rowData}
        applyType={state.applyType}
      />
    </div>
  );
};
export default connect(({ global }) => ({
  menuCode: global.configure.menuCode,
  buttonPermissions: global.configure.buttonPermissions,
}))(placeType);
